package com.junma.sql;

import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.lang.reflect.Field;

/**
 * 根据实体类创建sql语句，带注释
 *
 * @author huan
 */
@RestController
@AllArgsConstructor
//@RequestMapping("")
public class CreateSqlByClass {
    public static void main(String[] a) {
        Class<Slide> c = Slide.class;
        String tableName = null;
        if (c.getAnnotation(TableName.class) != null) {
            tableName = c.getAnnotation(TableName.class).value();
        }
        // 生成的sql语句的位置
        String outputPath = "D:\\excel\\user.txt";
        StrBuilder sb = new StrBuilder();
        String sql = generateTableSql(c, tableName);
        sb.append(sql);
        sb.append("\n");
        writeFile(sb.toString(), outputPath);

        System.out.println(tableName + "生成结束");

    }

    public static void writeFile(String content, String outputPath) {
        File file = new File(outputPath);
        System.out.println("文件路径: " + file.getAbsolutePath());
        // 输出文件的路径
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter out = null;

        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file, true);
            osw = new OutputStreamWriter(fos);
            out = new BufferedWriter(osw);
            out.append(content);
            out.newLine();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String generateTableSql(Class obj, String tableName) {
        if (tableName == null || tableName.equals("")) {
            tableName = obj.getName();
            tableName = tableName.substring(tableName.lastIndexOf(".") + 1);
            tableName = StrUtil.toUnderlineCase(tableName);
        }

        Field[] fields = obj.getDeclaredFields();

        String column;

        StringBuilder sb = new StringBuilder();

        sb.append("drop table if exists ").append(tableName).append(";\r\n");

        sb.append("\r\n");

        sb.append("create table ").append(tableName).append("(\r\n");

        //主键
        sb.append("`id` bigint(64) NOT NULL COMMENT '主键',");
        sb.append("\n");

        for (Field f : fields) {
            column = f.getName();

            Class<?> type = f.getType();
            // 遇到序列化则跳过当前循环
            if (column.contains("serialVersionUID")) {
                continue;
            }
            String typeName = type.getTypeName();
            sb.append("`");
            sb.append(StrUtil.toUnderlineCase(column));
            sb.append("`");

            if (typeName.equals("java.lang.Integer")) {
                sb.append(" int(11) ");
            } else if (typeName.equals("java.lang.Long")) {
                sb.append(" bigint(20) ");
            } else if (typeName.equals("java.lang.Float")) {
                sb.append(" float(11,5) ");
            } else if (typeName.equals("java.time.LocalDate")) {
                sb.append(" date ");
            } else if (typeName.equals("java.time.LocalDateTime") || typeName.equals("java.util.Date")) {
                sb.append(" datetime ");
            } else {
                sb.append(" varchar(" + 255 + ") ");
            }
            sb.append(" NULL DEFAULT NULL ");
            if (f.getAnnotation(ApiModelProperty.class) != null) {
                sb.append(" COMMENT '").append(f.getAnnotation(ApiModelProperty.class).value()).append("'");
            }
            sb.append(", ");

            sb.append("\n");
        }
        sb.append("`create_user` bigint(64) NULL DEFAULT NULL COMMENT '创建人',");
        sb.append("\n");
        sb.append("`create_dept` bigint(64) NULL DEFAULT NULL COMMENT '创建部门',");
        sb.append("\n");
        sb.append("`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',");
        sb.append("\n");
        sb.append("`update_user` bigint(64) NULL DEFAULT NULL COMMENT '修改人',");
        sb.append("\n");
        sb.append("`update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',");
        sb.append("\n");
        sb.append("`status` int(2) NULL DEFAULT NULL COMMENT '状态',");
        sb.append("\n");
        sb.append("`is_deleted` int(2) NULL DEFAULT NULL COMMENT '是否已删除',");
        sb.append("\n");
        sb.append(" PRIMARY KEY (`id`) USING BTREE");
        String sql = sb.toString();

        sql = sb.substring(0, sql.length()) + "\n) " + "ENGINE = INNODB DEFAULT CHARSET = utf8mb4;";
        return sql;
    }
}
